package com.stenio.fancat.util;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Created by stenio on 2018/5/24.
 */
public class JsonUtil {

	private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

	private static final ObjectMapper OM = new ObjectMapper();

	public static <T> String toJson(T type) {
		try {
			return OM.writeValueAsString(type);
		} catch (JsonProcessingException e) {
			logger.error("to json error", e);
			return null;
		}
	}

	public static <T> T parse(String jsonStr, Class<T> clazz) {
		try {
			return OM.readValue(jsonStr, clazz);
		} catch (IOException e) {
			logger.error("json format error", e);
			return null;
		}
	}

	/**
	 * 判断字符串是否为json类型的字符串，true为是json字符串
	 * 
	 * @param jsonStr
	 *            字符串
	 * @return true为是json字符串
	 */
	public final static boolean isJson(String jsonStr) {
		try {
			JSONObject.parseObject(jsonStr);
		} catch (JSONException ex) {
			logger.error("to json error", ex);
			try {
				JSONObject.parseArray(jsonStr);
			} catch (JSONException ex1) {
				logger.error("to json error", ex1);
				return false;
			}
		}
		return true;
	}
}
